package ru.paswd.marketprice.distance.calculator.impl;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import ru.paswd.marketprice.distance.calculator.DistanceCalculator;

@Component
@ConditionalOnProperty(name = "app.distance.calculation.method", havingValue = "plane")
public class PlaneDistanceCalculator implements DistanceCalculator {

    private static final double EQUATOR_LENGTH = 40075696.;
    private static final double MERIDIAN_LENGTH = 40008550.;

    @Override
    public int getDistance(double lat1, double lng1, double lat2, double lng2) {
        double latDistance = getLatDistance(lat1, lat2);
        double lngDistance = getLngDistance(lat1, lng1, lat2, lng2);

        return Long.valueOf(
                Math.round(
                        Math.sqrt(Math.pow(latDistance, 2) + Math.pow(lngDistance, 2))))
                .intValue();
    }

    private double getLatDistance(double lat1, double lat2) {
        double degreeLength = MERIDIAN_LENGTH / 360.;
        return Math.abs(lat1 - lat2) * degreeLength;
    }

    private double getLngDistance(double lat1, double lng1, double lat2, double lng2) {
        double lat = Math.abs(lat1 - lat2);
        double degreeLength = EQUATOR_LENGTH / 360. * Math.cos(Math.toRadians(lat));
        return Math.abs(lng1 - lng2) * degreeLength;
    }
}
